/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef SMART_SERVE_SERVICES_SERVER_SERVICE_SERVICE_H
#define SMART_SERVE_SERVICES_SERVER_SERVICE_SERVICE_H

#include "app/manager.h"
#include "assertion.h"
#include "smart_serve_log.h"
#include "model/manager.h"
#include "scheduler/scheduler.h"
#include "sensor/manager.h"
#include "service/client_api.h"
#include "service/config.h"
#include "service/config_loader.h"
#include "service/maintainer.h"
#include "session/manager.h"
#include <memory>

namespace OHOS {
namespace SmartServe {

class Service {
public:
    // API
    std::string Serve(const std::string& request);

    // 管理锁：管理 Model/Session 关系
    std::mutex msMgmtMutex_;
    Maintainer maintainer_;

    ModelManager modelManager_;
    SessionManager sessionManager_;
    AppManager appManager_;
    std::unique_ptr<Scheduler> scheduler_;
    SensorManager sensorManager_;
    ClientAPIHandler apiHandler_;

    // 单例
    static Service* Instance()
    {
        ASSERT(instance_ != nullptr);
        return instance_.get();
    }
    static bool Init()
    {
        SMART_SERVE_LOGD("[Service] Init Begin");
        Config config;
        if (!ConfigLoader::LoadFromFile("/etc/smart_serve/config.json", config)) {
            SMART_SERVE_LOGE("LoadFromFile failed");
            return false;
        }
        instance_ = std::unique_ptr<Service>(new Service());
        instance_->scheduler_->Init(config);
        SMART_SERVE_LOGD("[Service] Init End");
        return true;
    }
    static void Finalize()
    {
        SMART_SERVE_LOGD("[Service] Finalize Begin");
        instance_->Terminate();
        instance_ = nullptr;
        SMART_SERVE_LOGD("[Service] Finalize End");
    }

private:
    void Terminate();

    // 单例
    Service();
    static std::unique_ptr<Service> instance_;
};

} // namespace SmartServe
} // namespace OHOS

#endif // SMART_SERVE_SERVICES_SERVER_SERVICE_SERVICE_H
